/**
 * Class: AnotherReaderAPI
 * 
 * Version: Under Development
 * 
 * Description: This class provides access to the unofficial Google Reader API.
 * 
 * Copyright 2011 by Gregor M. Dutz/Maksim Tech. (maksim.tech@googlemail.com)
 */

/**
 * This file is part of AnotherReaderAPI.
 *
 * AnotherReaderAPI is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * AnotherReaderAPI is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with AnotherReaderAPI.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.maksimtech.aratestingunit;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;


public class AnotherReaderAPI {

	private String _username, _password, _auth, _client;
	private boolean loggedIn;
	
	AnotherReaderAPI() {
		loggedIn = false;
	}
	
	public String login(String username, String password) { // login to Google
		_client = "scroll";
		login(username, password, _client); // default Google client
		return _auth;	
	}
	
	public String login(String username, String password, String client) { // login to Google
		_username = username;
		_password = password;
		
		String[] authData = getSid();
		if (authData == null) {
			loggedIn = false;
			return null;
		}
		else {
			loggedIn = true;
			return _auth = authData[2];
		}
	}
	
	public JSONArray getUnreadCount() {
		if (loggedIn = true) {
			long  _timestamp = System.currentTimeMillis() / 1000;
			String received;
			BasicHeader headers[] = new BasicHeader[2];
		
			headers[0] = new BasicHeader("Authorization", "GoogleLogin auth=" + _auth);
			headers[1] = new BasicHeader("User-agent", _client);
		
			received = executeHttpGet("https://www.google.com/reader/api/0/unread-count?allcomments=true&output=json&ck=" + _timestamp+ "&client=" + _client, headers);
		
			if (received != null) {
				try {
					JSONObject json = new JSONObject(received);
					JSONArray nameArray=json.names();  
					JSONArray valueArray = json.toJSONArray(nameArray);
					return valueArray;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return(null);
	}
	
	public String getUserInfo() {
		return(null);
	}
	
	public JSONArray getFeedByURL(URI url, String sorting, boolean excludeRead, int maxElements, long since) {
		return(null);
	}
	
	public JSONArray getFeedsByLabel(String label, String sorting, boolean excludeRead, int maxElements, long since) {
		return(null);
	}
	
	public void getReadingList() {
		
	}
	
	public void getStarred() {
		
	}
	
	public void getBroadcast() {
		
	}
	
	public void getNotes() {
		
	}
	
	public boolean getLoginStatus()	{
		return loggedIn;
	}
	
	
	private String[] getSid() {
		String received;
		String[] authData = new String[3];
		
		received = executeHttpPost("https://www.google.com/accounts/ClientLogin?service=reader&Email=" + _username +"&Passwd=" + _password);
		
		if (received != null) {
			authData[0] = received.substring(received.indexOf("SID=") + 4, received.indexOf("LSID=")); // cut out SID
			authData[1] = received.substring(received.indexOf("LSID=") + 5, received.indexOf("Auth="));
			authData[2] = received.substring(received.indexOf("Auth=") + 5, received.length());
			return authData;
		}
		return null;
	}
	
	private String executeHttpGet(String uri) {
		return executeHttpGet(uri, null);
	}
	
	private String executeHttpGet(String uri, Header headers[]) {
		String line, received;
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(uri);
		
		if (headers != null) {
			httpGet.setHeaders(headers); // add headers
		}

		try {
			HttpResponse httpResponse = httpClient.execute(httpGet);
			//httpStatusHandler(httpResponse.getStatusLine().toString());
			// TODO add status-handling
			if (httpResponse != null) {
				HttpEntity httpEntity = httpResponse.getEntity();
				InputStream inputStream = httpEntity.getContent(); // read content to stream
			
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				StringBuilder stringBuilder = new StringBuilder();
				while ((line = bufferedReader.readLine()) != null) stringBuilder.append(line); // make string from stream
				received=stringBuilder.toString();
				
				return received;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
		return null;
	}
	
	private String executeHttpPost(String uri) {
		return executeHttpPost(uri, null);
	}
	
	private String executeHttpPost(String uri, Header headers[]) {
		String line, received;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(uri);
		
		if (headers != null) {
			httpPost.setHeaders(headers);
		}
		
		try {
			HttpResponse httpResponse = httpClient.execute(httpPost); // send request
			//httpStatusHandler(httpResponse.getStatusLine().toString());
			// TODO add status-handling
			if (httpResponse != null) {
				HttpEntity httpEntity = httpResponse.getEntity();
				InputStream inputStream = httpEntity.getContent(); // read content to stream
			
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				StringBuilder stringBuilder = new StringBuilder();
				while ((line = bufferedReader.readLine()) != null) stringBuilder.append(line); // make string from stream
				received=stringBuilder.toString();
				return received;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	
	private String httpStatusHandler(String httpStatus) {
		// TODO implement this
		return null;
	}
	
	
	
}
